$(function () {
  $('.imgcode').click(function () {
    // var url = api  + "captcha?type=math&randomStr=" +randomStr;
    // $(".imgcode").attr("src", url);
    getCode()
  });
  $('#btnSubmit').click(function () {
    submitHandler()
  });
  $("body").keyup(function (event) {
    if (event.keyCode == 13) {//keyCode=13是回车键
      $("#btnSubmit").click();
    }
  });
  getCode()
  getTenant();
});
//Date.now() + parseInt(Math.random() * 100)
var randomStr =  parseInt(Math.random() * 100);
var icon = "<i class='fa fa-times-circle'></i> ";
$("#signupForm").validate({
  rules: {
    tenant: {
      required: true
    },
    username: {
      required: true
    },
    password: {
      required: true
    },
    kaptcha: {
      required: true,
      remote: {
        type: "post",
        url: api + "/checkCode",
        cache: false,
        async: false,
        data: {
          randomStr: randomStr,
          code: function () {
            return $("#kaptcha").val();
          }
        }
      }
    }
  },
  messages: {
    tenant: {
      required: icon + "请选择租户",
    },
    username: {
      required: icon + "请输入您的登录名",
    },
    password: {
      required: icon + "请输入您的密码",
    },
    kaptcha: {
      required: icon + "验证码不能为空",
      remote: icon + "请输入正确的验证码",
    }
  }
})

function getCode() {
  $.ajax({
    type: "get",
    url: api + "/captcha?type=math&randomStr=" + randomStr,
    success: function (res) {
      $(".imgcode").attr("src", res);
      $("#kaptcha").val("");
      // randomStr = Date.now()+parseInt(Math.random()*100);
    }
  });
}

function getTenant() {
  $.ajax({
    type: "get",
    url: api + "/admin/tenant/list",

    success: function (res) {
      var options = []
      res.data.forEach(function (item) {
        options.push('<option value=' + item.id + '>' + item.name + '</option>')
      })
      $('#tenantSelect').append(options)
      if (storage.get('tenantId')) {
        $('#tenantSelect').val(storage.get('tenantId'))
      }
    }
  });
}

function submitHandler() {
  if ($.validate.form()) {
    $.modal.loading($("#btnSubmit").data("loading"));
    // $('#password').val(algorithmRequestParam($('#password').val()))
    // $("#signupForm").submit();
    var code = $("#kaptcha").val();
    var data = {
      username: $('#username').val(),
      password: algorithmRequestParam($('#password').val())
    }
//sca: c2NhOnNjYQ==
//test: dGVzdDp0ZXN0
    $.ajax({
      type: "post",
      url: api + "/auth/oauth/token?grant_type=password&randomStr=" + randomStr + "&code=" + code,
      data: data,
      dataType: 'json',
      headers: {
        "Authorization": 'Basic c2NhOnNjYQ==',
        "TENANT-ID": $("#tenantSelect").val(),
      },
      success: function (res) {
        window.location.href = '/pages/home/main'
        session.set('token', res.access_token)
        session.set('refresh_token', res.refresh_token)
        session.set('tenantId', res.user_info.tenantId)
        storage.set('tenantId', res.user_info.tenantId)
        session.set('userInfo', JSON.stringify({
          username: res.user_info.username,
          phone: res.user_info.phone,
          tenantId: res.user_info.tenantId,
          deptId: res.user_info.deptId,
          userId: res.user_info.id,
          avatar: res.user_info.avatar,
        }))
        var list = {}
        var permissions = res.user_info.authorities
        for (var i = 0; i < permissions.length; i++) {
          list[permissions[i].authority] = true
        }
        session.set('permissions', JSON.stringify(list))
        session.set('expires_in', res.expires_in)
      },
      error: function () {
        getCode()
      }
    });

  }
}

